#!/usr/bin/perl
use strict;
use warnings;
use Dancer ':script';
use Digest::MD5 qw(md5_hex);
use DBI;
use Cwd qw(abs_path);
use File::Basename qw(dirname);
print "Taracot installation script\nDatabase configuration\n\n";
my $root = dirname(abs_path($0));
$root =~s/\\/\//gm;
$root =~s/\/installation$//; 
push (@INC, $root.'/lib');
print "Loading Dancer config...\n";
Dancer::Config::setting('appdir', $root);
Dancer::Config::setting('confdir', $root);
Dancer::Config::load(); 
print "Do you wish to add MySQL user and create the database? [Y/n] ";
my $ans = <STDIN>;
chomp($ans);
if ($ans ne 'n') {
 my $database = config->{plugins}->{Database}->{database} || '';
 my $username = config->{plugins}->{Database}->{username} || '';
 my $password = config->{plugins}->{Database}->{password} || '';
 my $server = config->{plugins}->{Database}->{host} || '';
 print "Please enter the maximum number of connections per user [100]: ";
 my $wk = <STDIN>;
 chomp($wk);
 if (!$wk) {
 	print "- Setting 100 connections per user...\n";
 	$wk=100;
 }
 open(DATA, "taracot_db.sql");
 binmode(DATA);
 my $sqldb = join('', <DATA>);
 close(DATA);
 $sqldb=~s/\[database\]/$database/igm;
 $sqldb=~s/\[user\]/$username/igm;
 $sqldb=~s/\[password\]/$password/igm;
 $sqldb=~s/\[server\]/$server/igm;
 $sqldb=~s/\[workers\]/$wk/igm;
 open(DATA, ">taracot_db_import.sql");
 binmode(DATA);
 print DATA $sqldb;
 close(DATA);
 print "Importing SQL commands... Use your root MySQL password below\n";
 system('mysql -u root -p < taracot_db_import.sql');
 unlink 'taracot_db_import.sql';
}
print "Connecting to the database...\n";
my $dbh;
my $DSN = 'DBI:mysql:'.config->{plugins}->{Database}->{database}.':'.config->{plugins}->{Database}->{host};
$dbh = DBI->connect($DSN, config->{plugins}->{Database}->{username}, config->{plugins}->{Database}->{password});
my $sth = $dbh->prepare("SET NAMES 'utf8'");
$sth->execute();
$sth->finish();
$sth = $dbh->prepare("SET CHARACTER SET 'utf8'");
$sth->execute();
$sth->finish();
print "Opening SQL schema...\n";
open(DATA, "taracot.sql");
my @sql = <DATA>;
close(DATA);
print "Processing SQL requests...\n";
foreach my $req (@sql) {	
	$sth = $dbh->prepare($req);
	$sth->execute();
	$sth->finish();
}
print "\nNeed to create a new administrator.\n\nPlease enter username: ";
my $username = <STDIN>;
chomp($username);
print "Please enter password: ";
my $password = <STDIN>;
chomp($password);
print "Creating new user...\n";
$sth = $dbh->prepare("INSERT INTO taracot_users SET status=2, username=".$dbh->quote($username).", password=".$dbh->quote(md5_hex(config->{salt}.$password)).", regdate=".time);
$sth->execute();
$sth->finish();
print "Disconnecting from the database...\n";
$dbh->disconnect();
$dbh = undef;
print "\nInstallation complete!\n";